package com.emptyMe.org.controller;

import com.emptyMe.basic.utils.AjaxResult;
import com.emptyMe.org.domain.Emp;
import com.emptyMe.org.domain.EmpDTO;
import com.emptyMe.org.query.EmpQuery;
import com.emptyMe.org.service.IEmpService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/employee")
@Api(tags = "管理员接口", description = "管理员接口详细描述")
public class EmpController {

    @Resource
    private IEmpService service;

    @PostMapping("login")  // account:账户
    @ApiOperation(value = "登录功能实现")
    public AjaxResult login(@RequestBody Emp emp) {
        try {
            EmpDTO dto = service.login(emp);
            return AjaxResult.me(dto);
        } catch (Exception e) {
            return AjaxResult.me(false, e.getMessage());
        }
    }

    @PostMapping("empLogout")
    @ApiOperation(value = "退出登录")
    public AjaxResult logout() {
        return service.logout();
    }


    @PutMapping
    @ApiOperation(value = "添加或修改管理员", notes = "如果有id就修改，没有就添加")
    public AjaxResult addOrUpdate(@RequestBody Emp emp) {
        try {
            service.SaveEmp(emp);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me(false, "更新或添加失败" + e.getCause());
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除商品")
    public AjaxResult del(@PathVariable List<Long> id) {
        try {
            service.DelEmp(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me(false, "删除失败" + e.getCause());
        }
    }

    @DeleteMapping("/delMany")
    @ApiOperation(value = "批量删除")
    public AjaxResult delAll(@RequestBody List<Emp> emps) {
        try {
            ArrayList<Long> list = new ArrayList<>();
            for (Emp emp : emps) {
                list.add(emp.getId());
            }
            service.DelEmp(list);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me(false, "删除失败" + e.getCause());
        }
    }

    @PostMapping
    @ApiOperation(value = "分页查询")
    public AjaxResult findAll(@RequestBody EmpQuery query) {
        PageInfo<Emp> info = service.findAllEmp(query);
        return AjaxResult.me(info);
    }
}
